import simpy
import logging
from .base import BaseClock

logger = logging.getLogger('SimpleClock')

class SimpleClock(BaseClock):

    def __init__(self, env, freq_hz, init_value, max_value, skew_ppm):
        self.env = env
        self.freq_hz = freq_hz
        self.skew_ppm = skew_ppm
        self.max_value = max_value
        self.clk = init_value
        self.clock_event = simpy.Event(self.env)
        self.period = 1.0 / self.freq_hz
        self.true_period = self.period / (1.0 + self.skew_ppm / 1000000.0)
        logger.debug(f'true period {self.true_period}')

    def wait_clock(self):
        return self.clock_event
    
    def clock(self):
        return self.clk

    def get_period(self):
        return self.true_period

    def set_clock(self, clk):
        self.clk = clk
    
    def start(self):
        
        while True:
            
            yield self.env.timeout(self.true_period)
            self.clk += 1
            if self.clk == self.max_value:
                self.clk = 0
            logger.debug(f'{self.env.now:.6f} clk:{self.clk}')
            self.clock_event.succeed()
            self.clock_event = simpy.Event(self.env)